import 'package:cached_network_image/cached_network_image.dart';
import 'package:cunyutech_flutter_ui/src/theme/main.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

class CYNetworkImage extends StatelessWidget {
  CYNetworkImage.assetNetwork({
      Key key,
      this.image,
      this.bundle,
      this.placeholderScale = 1.0,
      this.imageScale = 1.0,
      this.excludeFromSemantics  = false,
      this.imageSemanticLabel,
      this.fadeOutDuration = const Duration(milliseconds: 300),
      this.fadeOutCurve = Curves.easeOut,
      this.fadeInDuration = const Duration(milliseconds: 700),
      this.fadeInCurve = Curves.easeIn,
      this.width,
      this.height,
      this.fit = BoxFit.cover,
      this.alignment = Alignment.center,
      this.repeat = ImageRepeat.noRepeat,
      this.matchTextDirection = false,
      @required this.loadFail,
    }) : super(key: key);

      final String image;
      final AssetBundle bundle;
      final double placeholderScale;
      final double imageScale;
      final bool excludeFromSemantics;
      final String imageSemanticLabel;
      final Duration fadeOutDuration;
      final Curve fadeOutCurve;
      final Duration fadeInDuration;
      final Curve fadeInCurve;
      final double width;
      final double height;
      final BoxFit fit;
      final Alignment alignment;
      final ImageRepeat repeat;
      final bool matchTextDirection;
      final String loadFail;
  

  @override
  Widget build(BuildContext context) {

    if(
      image == null ||
      (image!=null && !image.contains(RegExp(r"^http")))
    ) {
      return Image.asset(loadFail, width: width, height: height, fit: BoxFit.cover);
    }
    var cs = CYThemeData.of(context);
    return CachedNetworkImage(
      imageUrl: image,
      fadeInCurve: fadeInCurve,
      fadeInDuration: fadeInDuration,
      fadeOutCurve: fadeOutCurve,
      fadeOutDuration: fadeOutDuration,
      placeholder: (BuildContext _context, String url) {
        return Container(
          width: width, 
          height: height,
          constraints: BoxConstraints(
            minWidth: 10,
            minHeight: 10
          ),
          color: cs.backColorSystem.secondaryColor,
        );
      },
      errorWidget: (BuildContext _, String url, Object __ ) {
        return Image.asset(loadFail, width: width, height: height, fit: BoxFit.cover);
      },
      width: width,
      height: height,
      fit: fit,
      alignment: alignment,
      matchTextDirection: matchTextDirection,
      repeat: repeat,
    );
  }
}